/**
* Appcelerator Titanium Platform
* Copyright (c) 2009-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
**/
// Code is stripped-down version of Tweetanium, to expose new structure paradigm
Ti.include("newsSlider.js");

(function(){
	S.news = {};
	S.ui.newsSlider = newsSliderView();
	S.ui.createView = function(view){
		
		if (view != "news") return null;
		S.news.json = null;
		
		// Initial XHR Call
		S.Xhr({
		    onload: function(e) {
		        //Ti.API.debug(this.responseText);
		        S.news.json = JSON.parse(this.responseText)
				populateNewsView(S.news.json);
		    },
		    onerror: function(e) {
		        Ti.API.debug(e.error);
		        alert(e.error);
		    },
		    method: "GET",
		    url: "http://platform.electiontools.org:80/drupal6/api/views/story_view.json?p=0&l=100"
		});
		
		// Create new view
		var thisView = Ti.UI.createView(S.combine($$.contentView, {id: 'newsView'}));
		
		// Share bar display toggle
		S.ui.shareBarIsVisible = true;
		var shareBar;
		
		// Dynamic footer
		var footerContainer;
		S.ui.footerIsVisible = false;
		
		// Populates an individual news row
		function populateNewsRow(jsonItem, index) {

			// News row
			var row = Ti.UI.createView(S.combine({id: 'newsRow_' + index}, $$.newsTableRow));
			
			// JSON values
			//var newsItemId = jsonItem['nid'];
			var newsItemImage = (jsonItem['field_image'][0] != null) ? jsonItem['field_image'][0]['filepath'] : null;

			// Borders
			//var borderTop = Ti.UI.createView(S.combine($$.newsTableRowBorderTop));
			if (index > 0) row.add(Ti.UI.createView(S.combine({id: 'newsRowBorder_' + index}, $$.newsTableRowBorderBottom)));
			//row.add(borderTop);

			// Title
			row.add(Titanium.UI.createLabel(S.combine({text: jsonItem['title'], id: 'newsRowTitle_' + index},$$.newsRowTitle)));
			
			// Image
			if (newsItemImage != null) {
				var imgView = Ti.UI.createImageView(S.combine({image:"http://platform.electiontools.org/drupal6/" + newsItemImage, id: 'newsRowImage_' + index}, $$.newsRowImage));
				row.add(imgView);
			}
					
			// Created
			row.add(Titanium.UI.createLabel(S.combine({text: S.timeDifference(new Date().getTime(), jsonItem['created']*1000), id: 'newsRowDate_' + index},$$.newsRowCreated)));


			
			// Adding the listener for click event
			row.addEventListener('click',function(e){
				// Get the article id
				var id = (e.source.id) ? e.source.id.split("_")[1] : 0;
				
				// Creating new window for slider
				newsSliderWindow = sliderWindow(S.news.json, id);
				newsSliderWindow.open();
			});
			
			return row;
		}
		
		// News story page
		function populateNewsStoryPage(jsonItem, idx) {
			
			var newsStoryPage = Ti.UI.createScrollView(S.combine($$.newsStoryPage, {id: 'newsPage_' + idx}));

			// Inner container
			var innerContainer = Ti.UI.createView(S.combine($$.newsStoryInnerContainer));
			innerContainer.add(Titanium.UI.createLabel(S.combine($$.topPadding)));
			
			// Image
			var newsItemImage = (jsonItem['field_image'][0] != null) ? jsonItem['field_image'][0]['filepath'] : null;
			if (newsItemImage != null) {
				var imgView = Ti.UI.createImageView(S.combine({image:"http://platform.electiontools.org/drupal6/" + newsItemImage}, $$.newsStoryImage));
				innerContainer.add(imgView);
			}
						
			// Title
			var titleLabel = Ti.UI.createLabel(S.combine({text: jsonItem['title']}, $$.newsStoryTitle));
			innerContainer.add(titleLabel);
			
			// Body container
			var bodyLabel = Ti.UI.createLabel(S.combine({text: jsonItem['body']}, $$.newsStoryBody));
			innerContainer.add(bodyLabel);
			innerContainer.add(Titanium.UI.createLabel(S.combine($$.bottomPadding)));
			

			newsStoryPage.add(innerContainer);
			
			// Hide tabs when the content is scrolled
			newsStoryPage.addEventListener('scroll',function(e){
				
				// Getting the content height
				var contentHeight = (e.source.children[0]) ? e.source.children[0].size.height : $$.platformHeight;
				var t = contentHeight - $$.platformHeight;
				
				//Ti.App.fireEvent("app:msg",{msg:"e.y:" + e.y + "\ncontentHeight" + contentHeight + "\n$$.platformHeight:" + $$.platformHeight + "\nt:" + t});
				
				// Hide tabs only when the content is scrolled more than 0 (e.y > 0)
				if ((e.y*1 > S.ui.layout.tabSize && e.y*1 < t) && S.ui.shareBarIsVisible){
					Ti.App.fireEvent("app:shareBarHide");

				} 
				
				// Show tabs when the content is scrolled to the bottom limits
				if ((e.y*1 >= t || e.y*1 <= S.ui.layout.tabSize) && !S.ui.shareBarIsVisible){
					Ti.App.fireEvent("app:shareBarShow");
				}
				
				// Show the footer 
				if (e.y*1 >= t && !S.ui.footerIsVisible) {
					Ti.App.fireEvent("app:footerShow");
				}

				// Hide the footer 
				if (e.y*1 < t && S.ui.footerIsVisible) {
					Ti.App.fireEvent("app:footerHide");
				}
				
			});		
						
			return newsStoryPage;
		}
		
		function createThumbnail(jsonItem, idx) {
			var tView = Ti.UI.createView(S.combine({left: (S.ui.layout.tabSize - 10)*idx}, $$.thumbnailView));
			
			// Image
			var newsItemImage = (jsonItem['field_image'][0] != null) ? jsonItem['field_image'][0]['filepath'] : null;
			if (newsItemImage != null) {
				var imgView = Ti.UI.createImageView(S.combine({image:"http://platform.electiontools.org/drupal6/" + newsItemImage, id: 'thumbnailImage_' + idx}, $$.newsRowImage));
				tView.add(imgView);
			}
	
			return tView;
		}
				
		function sliderWindow(json, index) {

			// New window
			var sWindow = Ti.UI.createWindow(S.combine($$.newsSliderWindow));
			
			// Horizontal slider
			var newsArticleSlider = Ti.UI.createScrollableView(S.combine($$.newsArticleSlider,{id:'newsArticleSlider', horizontalBounce:true}));
			
			// Header for Slider Window
			shareBar = Ti.UI.createView(S.combine($$.shareBar));
			
			// Close button
			var sliderCloseButton = Ti.UI.createView(S.combine($$.sliderCloseButton));
			sliderCloseButton.addEventListener('click', function(e) {
				sWindow.close();
			});

			shareBar.add(Ti.UI.createLabel(S.combine({text: 'share/social/search'}, $$.shareBarLabel)));
			shareBar.add(sliderCloseButton);
			
			// man views container
			var views = [];
			
			// Add views to news slider
			views.push(populateNewsStoryPage(json[i], i));
			
			// News slider containing full stories
			newsArticleSlider.views = views;	
			
			// Setting the default view
			newsArticleSlider.scrollToView(index*(1));			


			
			// Top padding
			sWindow.add(Titanium.UI.createLabel(S.combine($$.topPadding)));
						
			// Adding all to the window
			sWindow.add(shareBar);
			sWindow.add(newsArticleSlider);
			
			// Bottom padding
			sWindow.add(Titanium.UI.createLabel(S.combine($$.bottomPadding)));
								
			
								
			/* LISTENERS */	
			sWindow.addEventListener("paginator:update",function(e){

				//Ti.App.fireEvent("app:msg",{msg: "index: " + e.index});

			});
			

			newsArticleSlider.addEventListener("scroll",function(e){
				// Updating the page indicator
				currentPageIndicator.left = paginationItemWidth * newsArticleSlider.currentPage;
			});
							
			sWindow.addEventListener("click",function(e){
				// Showing the share bar on click
				if (S.ui.shareBarIsVisible) {
					Ti.App.fireEvent("app:shareBarShow");
				}
			});						
			
							

			/* Temp
			 * Message view
			 */
			var msgview = Ti.UI.createView({opacity:0,zIndex:10,width:S.ui.properties.platformWidth-100,left:50,top:230,height:100}),
			msglabel = Ti.UI.createLabel($$.Label);
			msgview.add(msglabel);
		
			Ti.App.addEventListener("app:msg",function(e){
				//Ti.API.log(e);
				msglabel.text = e.msg;
				msgview.backgroundColor = e.error ? "red" : "white";
				msgview.opacity = 1;
				msgview.animate({
					opacity: 0,
					duration: 1500
				});
			});
		
			sWindow.add(msgview);
			
			
												
			return sWindow;
		}
		

		// Populates the news view
		function populateNewsView(json, append) {
			
			// Top padding
			thisView.add(Titanium.UI.createLabel(S.combine($$.topPadding)));

			for (var i = 0; i < json.length; i++) {

				// Add rows to default news list
				thisView.add(populateNewsRow(json[i], i));
				
			}

			// Bottom padding
			thisView.add(Titanium.UI.createLabel(S.combine($$.bottomPadding)));
			
			
			/* LISTENERS *
			 * 
			 */

			// Hiding the share bar
			Ti.App.addEventListener("app:shareBarHide",function(e){
		    	S.ui.shareBarIsVisible = false;
				// Animation for tabs
				var tabsHideAnimation = Titanium.UI.createAnimation();
				tabsHideAnimation.duration = 350;
				//tabsHideAnimation.opacity = 0;
				tabsHideAnimation.top = (S.ui.layout.tabSize/2)*(-1);
				shareBar.animate(tabsHideAnimation);
			});			
				
			// Showing the share bar
			Ti.App.addEventListener("app:shareBarShow",function(e){
				S.ui.shareBarIsVisible = true;
				//Ti.App.fireEvent("app:msg",{msg: "tabs show event fired"});
				var tabsShowAnimation = Titanium.UI.createAnimation();
				tabsShowAnimation.duration = 150;
				//tabsShowAnimation.opacity = 1;
				tabsShowAnimation.top = 0;
				shareBar.animate(tabsShowAnimation);
			});			
			
			// Hiding the thumbnail scroller
			Ti.App.addEventListener("app:footerHide",function(e){
		    	S.ui.footerIsVisible = false;
				// Animation for tabs
				var footerHideAnimation = Titanium.UI.createAnimation();
				footerHideAnimation.duration = 350;
				footerHideAnimation.opacity = 0;
				footerHideAnimation.bottom = (S.ui.layout.tabSize)*(-1);
				footerContainer.animate(footerHideAnimation);
			});			
				
			// Showing the thumbnail scroller
			Ti.App.addEventListener("app:footerShow",function(e){
				S.ui.footerIsVisible = true;
				//Ti.App.fireEvent("app:msg",{msg: "tabs show event fired"});
				var footerShowAnimation = Titanium.UI.createAnimation();
				footerShowAnimation.duration = 150;
				footerShowAnimation.opacity = 1;
				footerShowAnimation.bottom = 0;
				footerContainer.animate(footerShowAnimation);
			});	
						

		}


	
		return thisView;

	};
	

})();